<?php
namespace app\modules\mch\models\purchase;
use app\models\Purchase;
use app\modules\mch\models\MchModel;
use app\models\User;
use yii\data\Pagination;

class PurchaseForm extends MchModel
{
    public $store_id;
    public $model;
    public $user_id;
    public $is_share;
    public $num;


    public function rules()
    {
        return [
            [['store_id', 'user_id'], 'integer'],
        ];
    }

    public function attributeLabels() 
    { 
        return [ 
            'id' => 'ID',
            'store_id' => 'Store ID',
            'user_id' => '用户',
        ]; 
    }

    public function search()
    {

        $query = Purchase::find()
            ->where([
                'store_id' => $this->store_id,
                'is_delete' => 0
            ])->with(['user' => function ($query) {
                $query->where([
                    'store_id' => $this->store_id,
                    'is_delete' => 0
                ])->select('id, nickname,avatar_url');
            }]);


        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);

        $list = $query->limit($pagination->limit)->offset($pagination->offset)->orderBy(['create_time' => SORT_ASC, 'id' => SORT_DESC])->asArray()->all();



        foreach($list as $k => $v){
            $attrs = json_decode($v['attr'],true);
            $name = '';
            foreach($attrs as $v1){
                $name .= $v1['attr_group_name'].':'.$v1['attr_name'].';';
            }
            $list[$k]['attrs'] = $name; 
        }

        return [
            'list'=>$list,
            'pagination'=>$pagination
        ];

    }



    public function save()
    {
        if (!$this->validate()) {
            return $this->getErrorResponse();
        }
		$this->model->is_share = $this->is_share;
        $this->model->num = $this->num;
       
        if($this->model->save()){
			return [
				'code' => 0,
				'msg' => "设置成功",
			];
		}
    }
}